package org.bigmarketapi.gatewaysdk.annotations;

import lombok.extern.slf4j.Slf4j;
import org.bigmarketapi.gatewaysdk.config.gatewaySDKProperties;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @BelongsProject: Gateway-SDK
 * @BelongsPackage: org.bigmarketapi.gatewaysdk.annotations
 * @Author: dujiaqi
 * @CreateTime: 2024-12-16  22:47
 * @Description: TODO
 * @Version: 1.0
 */
@Component
@Slf4j
public class gatewayApplication implements BeanPostProcessor {
    gatewaySDKProperties gatewaySDKProper;

    public gatewayApplication(gatewaySDKProperties gatewaySDKProper) {
        this.gatewaySDKProper = gatewaySDKProper;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //寻找带有gatewayClass注解的类
        final gatewayClass gatewayClass = bean.getClass().getAnnotation(gatewayClass.class);
        if (gatewayClass != null) {
            log.info("接口名称： {}, 版本号: {}", gatewayClass.interfaceName(), gatewayClass.version());
        }
        final Method[] methods = bean.getClass().getMethods();
        for (Method method : methods) {
            final gatewayMethod gatewayMethod = method.getAnnotation(gatewayMethod.class);
            if (gatewayMethod == null) {
                continue;
            }
            //获取method上的参数
            final Class<?>[] types = method.getParameterTypes();
            String join;
            if (types.length == 0) {
                join = "";
            }
            join = String.join(",", Arrays.stream(types).map(Class::getName).collect(Collectors.toList())
            );
            log.info("join: {}", join);
            //去掉最后一个“，”号
            String substring;
            if (join.contains(",")) {
                substring = join.substring(0, join.toString().lastIndexOf(","));
            } else {
                substring = join;
            }
            log.info("\n应用注册：方法信息 \nsystemId: {} \ninterfaceId: {} \nmethodId: {} \nmethodName: {} \nparameterType: {} \nuri: {} \nhttpCommandType: {} \nauth: {}",
                    gatewaySDKProper.getSystemId(),
                    bean.getClass().getName(),
                    method.getName(),
                    gatewayMethod.methodName(),
                    substring,
                    gatewayMethod.URL(),
                    gatewayMethod.httpMethodCommand(),
                    gatewayMethod.isAuth());
        }
        return bean;
    }
}
